package net.lab1024.sa.admin.util;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.Requests;
import net.lab1024.sa.base.common.util.SmartStringUtil;
import net.lab1024.sa.base.constant.RedisKeyConst;
import net.lab1024.sa.base.module.support.redis.RedisService;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Component
public class MtcyUtils {

    @Autowired
    RedisService redisService;

    @Value("${local.ip:127.0.01}")
    String localIp;

    public String getShopList(String cookieStr) {
        String url = "https://waimaie.meituan.com/api/poi/poiList";
        OkHttpClient client = getClient();
        Map<String, String> queryParamMap = getQueryParamMap(cookieStr);
        String queryParamStr = SmartStringUtil.makeQueryParam(queryParamMap);
        String mtgsig = makeMtgsig(url, "POST", queryParamMap.get("WEBDFPID").split("-")[0], queryParamMap, new HashMap<>());
        String requestUrl = url + "?" + queryParamStr + "&mtgsig=" + SmartStringUtil.encodeStr(mtgsig);
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(requestUrl)
                .method("POST", body)
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9,ko;q=0.8")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Connection", "keep-alive")
                .addHeader("Origin", "https://e.waimai.meituan.com")
                .addHeader("Pragma", "no-cache")
                .addHeader("Referer", "https://e.waimai.meituan.com/")
                .addHeader("Sec-Fetch-Dest", "empty")
                .addHeader("Sec-Fetch-Mode", "cors")
                .addHeader("Sec-Fetch-Site", "same-origin")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36")
                .addHeader("sec-ch-ua", "\"Chromium\";v=\"134\", \"Not:A-Brand\";v=\"24\", \"Google Chrome\";v=\"134\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("Cookie", cookieStr)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Host", "waimaie.meituan.com")
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String getMtRequestUrl(String cookstr, Integer pageNo) {
        String url = "https://waimaieapp.meituan.com/gw/bizproduct/v3/food/r/spuListV2";
        Map<String, String> cookieMap = SmartStringUtil.cookieStrConvert(cookstr);
        Map<String, String> queryParamMap = getQueryParamMap(cookstr);
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("opType", 0);
        bodyMap.put("queryCount", 0);
        bodyMap.put("pageNum", pageNo);
        bodyMap.put("pageSize", 30);
        bodyMap.put("wmPoiId", cookieMap.get("wmPoiId"));
        bodyMap.put("needAllCount", false);
        bodyMap.put("needTagList", true);
        bodyMap.put("scenario", 0);
        String mtgsig = makeMtgsig(url, "POST", cookieMap.get("a3"), queryParamMap, bodyMap);
        String queryParamStr = SmartStringUtil.makeQueryParam(queryParamMap);
        return queryParamStr + "&mtgsig=" + SmartStringUtil.encodeStr(mtgsig);
    }

    private String makeMtgsig(String url, String method, String a3, Map<String, String> queryMap, Map<String, Object> bodyMap) {
        String postUrl = "";
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("a3", a3);
        if ("get".equals(method.toLowerCase())) {
            postUrl = "http://www.mtgsig.com:18086/api/mt/mtgisg_get";
        } else {
            postUrl = "http://www.mtgsig.com:18086/api/mt/mtgisg_post";
            paramsMap.put("data", queryMap);
        }
        paramsMap.put("params", bodyMap);
        paramsMap.put("url", url);
        Map<String, Object> heardMap = new HashMap<>();
        heardMap.put("Content-Type", "application/json");
        String readToText = Requests.post(postUrl)
                .headers(heardMap)
                .jsonBody(paramsMap)
                .timeout(50000)
                .send().readToText();
        //log.info("postMtgsig:{}", readToText);
        return JSONObject.parseObject(readToText).getString("mtgisg");
    }

    private Map<String, String> getQueryParamMap() {
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("yodaReady", "h5");
        dataMap.put("csecplatform", "4");
        dataMap.put("csecversion", "2.4.0");
        return dataMap;
    }

    private Map<String, String> getQueryParamMap(String cookieStr) {
        Map<String, String> cookieMap = SmartStringUtil.cookieStrConvert(cookieStr);
        Map<String, String> dataMap = getQueryParamMap();
        dataMap.put("region_id", cookieMap.get("region_id"));
        dataMap.put("region_version", cookieMap.get("region_version"));

        return dataMap;
    }

    private OkHttpClient getClient() {
        String ip = redisService.get(RedisKeyConst.Support.PROXY_IP + localIp);
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        if (StringUtils.isNoneBlank(ip)) {
            String[] ips = ip.split(",");
            Random r = new Random();
            int i = r.nextInt(ips.length);
            String[] tip = ips[i].split(":");
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(tip[0], Integer.parseInt(tip[1])));
            return builder.proxy(proxy).build();
        } else {
            return builder.build();
        }

    }
}
